#include "../common/Common.h"
#include "LogisticRegStochastic.cpp"

using namespace bouguerra;

IplImage *result;
CvMat* thetas = cvCreateMat(1, 4, CV_32FC1);
float threshold = .5;

void print_usage()
{
	printf("Usage: program.exe <regression model> <work> <file_path>\n");
	printf("<regression model>: 0(color differences) , 1 (background differences)\n");
	printf("<work> : -test_image, -test_video\n");
	printf("<file_path>: for -test_image: *.jpg\n");
	printf("<file_path>: for -test_video: *.avi\n");
	return;
}


void run(IplImage* inputImage) {
	if (result == NULL || (result->width != inputImage->width && result->height
			!= inputImage->height))
		result = cvCreateImage(cvGetSize(inputImage), IPL_DEPTH_32F, 1);


	int startX = 0;
	int startY = 0;
	int endX = inputImage->width;
	int endY = inputImage->height;

	float b, g, r;
	float sigma, hypothesis;

	for (int y = startY; y < endY; y++) {
		float* ptr_out = (float*) (result->imageData + y * result->widthStep);
		uchar* ptr_test = (uchar*) (inputImage->imageData + y
				* inputImage->widthStep);

		for (int x = startX; x < endX; x++) {
			b = ptr_test[3 * x];
			g = ptr_test[3 * x + 1];
			r = ptr_test[3 * x + 2];

			float theta_0 = *(float*) (thetas->data.ptr);
			float theta_1 = *(float*) (thetas->data.ptr + 4);
			float theta_2 = *(float*) (thetas->data.ptr + 8);
			float theta_3 = *(float*) (thetas->data.ptr + 12);


			sigma = theta_0 + theta_1 * b + theta_2 * g + theta_3 * r;
			hypothesis = 1.0 / (1.0 + exp(-1.0 * sigma));
			ptr_out[x] = hypothesis > threshold ? 1 : 0;

		}
	}
}

int main(int argc, char* argv[]) {
	if (argc != 4){
		print_usage();
		return 0;
	}



	bool isVideo =  !strcmp(argv[2],"-test_video" );

	LogisticRegStochastic logisticReg;
	logisticReg.model = atoi(argv[1]);

	LogisticRegHelper helper;
	helper.loadThetasFromFile(thetas,THETAS_FILE );
	cvNamedWindow("regression", CV_WINDOW_AUTOSIZE);
	IplImage* inputImage;

	if(isVideo)
	{
		CvCapture* capture = cvCreateFileCapture(argv[3]);
		while(1)
		{
			inputImage = cvQueryFrame( capture );
			logisticReg.manipulate(inputImage);
			if(!inputImage) break;
			run(inputImage); //Run lowleveldetection ( logistic regression ).
			cvShowImage("regression", result); //display the lowLevelDetector result
			cvWaitKey(30);
		}
	}
	else
	{

		inputImage = cvLoadImage(argv[3]);
		logisticReg.manipulate(inputImage);
		run(inputImage); //Run lowleveldetection ( logistic regression ).
		cvShowImage("regression", result); //display the lowLevelDetector result
		cvWaitKey(5000);
	}
	//release memory
	cvReleaseImage(&inputImage);
	cvReleaseImage(&result);
}
